<template>
  <el-dialog title="欢迎使用导入小工具" :visible.sync="show" :close-on-click-modal="false" @close="close" custom-class="dialog-container" fullscreen center>
    <el-container>
      <el-header style="height:auto">
        <el-steps :active="stepIndex">
          <el-step v-for="(step, i) in steps" :key="`step_${i}`" :title="step.title" :icon="step.icon" ></el-step>
        </el-steps>
      </el-header>
      <el-main style="padding: 0 20px;">
        <template v-if="stepIndex == 0">
          <template v-if="batchId && importGroup.file.fileId">

          <el-form>
            <el-form-item>
              <img :src="fileTypes[importGroup.file.extensionName]" :alt="importGroup.file.fileName" />
            </el-form-item>
            <el-form-item>
              <el-link :href="downloadUrl" icon="el-icon-download">{{ importGroup.file.fileName }}</el-link>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="reset">重新上传</el-button>
            </el-form-item>
          </el-form>

          </template>
          <template v-else>
            <el-upload
              drag
              :action="uploadUrl"
              :name="importerName"
              :headers="headers"
              :show-file-list="false"
              :before-upload="onBeforeUpload"
              :on-success="onUploaded"
              :on-error="onUploadError"
              accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              multiple>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">注意：文件不可超过{{maxFileLength}}KB</div>
            </el-upload>
          </template>
        </template>

        <template v-if="stepIndex == 1">
          <el-tabs v-if="sheets&&sheets.length > 0" v-model="sheetName" @tab-click="tabClick" style="height:100%">
            <el-tab-pane v-for="(sheet, i) in sheets" :key="`sheet_${i}`" :label="sheet.sheetName" :name="sheet.sheetName">
              <el-container>
                <el-main style="padding:10px 0;">
                  <el-table height="100%" :data="sheet.dataTable.result.rows" border style="width: 100%" :row-style="rowStyle">
                    <el-table-column width="50" fixed="left" label="#" header-align="center" align="center">
                      <template slot-scope="scope">
                        {{scope.row.rowIndex + 1}}
                      </template>
                    </el-table-column>
                    <el-table-column v-for="column in sheet.dataTable.result.columns" :key="`sheet_${i}_${column.name}`" :label="column.displayName || column.name" min-width="100" resizable show-overflow-tooltip>
                      <template slot-scope="scope">
                        <template v-if="scope.row.editing">
                          <input v-model="scope.row.dataItem[column.name]"></input>
                        </template>
                        <template v-else>
                          {{scope.row.dataItem[column.name]}}
                        </template>
                      </template>
                    </el-table-column>
                    <el-table-column width="100" fixed="right" label="操作" header-align="center" align="center">
                      <template slot="header">
                        <el-button type="text" icon="el-icon-refresh-left" @click="undoAll(sheet)" title="撤消所有更改"></el-button>
                      </template>
                      <template slot-scope="scope">
                        <template v-if="scope.row.editing">
                          <el-button type="text" icon="el-icon-finished" @click="update(scope.row)"></el-button>
                          <el-button type="text" icon="el-icon-close" @click="scope.row.editing = false"></el-button>
                        </template>
                        <template v-else>
                          <el-button :disabled="scope.row.state == 'Removed'" type="text" icon="el-icon-edit" @click="scope.row.editing = true"></el-button>
                          <el-button :disabled="scope.row.state == 'Removed'" type="text" icon="el-icon-remove" @click="remove(scope.row)" title="删除"></el-button>
                          <el-button :disabled="scope.row.state == 'Unchanged'" type="text" icon="el-icon-refresh-left" @click="undo(scope.row)" title="撤消"></el-button>
                        </template>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-main>
                <el-footer style="height: auto;padding:0;">
                  <el-pagination v-on:current-change="preview(sheet)" :current-page.sync="sheet.previewRequest.pageIndex" :page-size="sheet.previewRequest.pageSize" layout="total, prev, pager, next" :total="sheet.dataTable.rowCount" ></el-pagination>
                </el-footer>
              </el-container>
            </el-tab-pane>
          </el-tabs>
          <div v-else>
            请先上传导入文件
          </div>
        </template>
        <template v-if="stepIndex == 2">
          <el-form>
            <el-form-item>
              <el-button type="primary" @click="accept">确认导入</el-button>
            </el-form-item>
          </el-form>
        </template>
        <template v-if="stepIndex == 3">
          <el-result icon="info" title="操作已完成">
            <template slot="subTitle">
              <el-descriptions v-for="summary in importGroup.summary" :key="summary.name" :column="3" size="small">
                <div slot="title">
                  <span>{{summary.name}}</span>
                </div>
                <el-descriptions-item label="数据总计">{{ summary.totalCount }}行</el-descriptions-item>
                <el-descriptions-item label="导入成功">{{ summary.successCount }}行</el-descriptions-item>
                <el-descriptions-item label="操作失败">{{ summary.failCount }}行</el-descriptions-item>
              </el-descriptions>
            </template>
            <template slot="extra">
            </template>
          </el-result>
        </template>
      </el-main>
    </el-container>

    <div slot="footer">
      <template v-if="stepIndex == 3">
        <el-button type="primary" size="medium" @click="show = false">返回</el-button>
      </template>
      <template v-else>
        <el-button type="primary" @click="prev">上一步</el-button>
        <el-button type="primary" @click="next">下一步</el-button>
      </template>
    </div>
  </el-dialog>
</template>
<script>
export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    importerName: {
      type: String,
      default: '',
    },
    maxFileLength: {
      type: Number,
      default: 102400
    }
  },
  data() {
    return {
      steps: [
        {
          title: '上传文件',
          icon: 'el-icon-upload'
        },
        {
          title: '预览数据',
          icon: 'el-icon-search'
        },
        {
          title: '导入结果',
          icon: 'el-icon-finished'
        }
      ],
      stepIndex: 0,
      batchId: null,
      importGroup: {
        file: {},
        summary: [
        // name: null,  //sheetName
        // successCount: 0, //成功记录数
        // failCount: 0,  //失败记录数
        ]
      },
      sheets: [],
      sheetName: null,
      fileTypes: {
        ".xls": require("@/assets/img/xls.png"),
        ".xlsx": require("@/assets/img/xlsx.png"),
      }
    };
  },
  computed: {
    show: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      },
    },
    uploadUrl(){
      return `${this.$service.import.upload}?importer=${this.importerName}`
    },
    downloadUrl(){
      return `${this.$service.import.load}?importer=${this.importerName}&batchId=${this.batchId}&fileId=${this.importGroup.file.fileId}`
    },
    headers(){
      return {
        Authorization: `Bearer ${this.$store.state.token}`
      }
    }
  },

  methods: {
    close(){
      this.init();
    },
    init(){
      this.stepIndex = 0;
      this.batchId = null;
      this.importGroup = {
        file: {},
        summary: [
        // name: null,  //sheetName
        // successCount: 0, //成功记录数
        // failCount: 0,  //失败记录数
        ]
      };
      this.sheets = [];
      this.sheetName = null;
    },
    prev(){
      this.stepIndex--;
      if (this.stepIndex < 0){
        this.stepIndex = 0;
      }
    },
    next(){
      this.stepIndex++;
      if (this.stepIndex > this.steps.length){
        this.stepIndex = this.steps.length ;
      }

    },
    cancel() {
      this.show = false;
    },
    undoAll(sheet){
      confirm('该操作将导致下表中当前的所有更改丢失，继续吗？', '提示', 'warn', ()=>{
        this.$service.import.undoAll({
          params: {
            importer: this.importerName
          },
          data: {
            batchId: this.batchId,
            fileId: this.importGroup.file.fileId,
            name: this.sheetName
          }
        }).then(r => {
          if (r.success)
            this.preview(sheet)
        });
      });
    },
    onUploaded(response, file){
      this.$store.commit("loading", false);
      if (response.success){
        let data = response.data;
        this.batchId = data.batchId;
        if (data.groups && data.groups.length > 0){
          this.importGroup = data.groups[0];
          this.loadPreview();
        }
      }
    },
    loadPreview(){
      this.sheets = [];
      for(let summary of this.importGroup.summary){
        let sheet = {
          sheetName: summary.name,
          previewRequest: {
            parameters:{
              batchId: this.batchId,
              fileId: this.importGroup.file.fileId,
              name: summary.name,  //sheetName
            },
            pageIndex: 1,
            pageSize: 20,
            sortField: null,
            sortDesc: false
          },
          dataTable: {
            result: {
              name: "",
              columns: [],
              rows: []
            },
            pageIndex: 1,
            pageSize: 20,
            pageCount: 0,
            rowCount: 0,
          }
        };
        this.sheets.push(sheet);

        this.preview(sheet);

        if (this.sheets.length > 0)
          this.sheetName = this.sheets[0].sheetName;
      }
    },
    preview(sheet){
      this.$service.import.preview({
        params: {
          importer: this.importerName
        },
        data: sheet.previewRequest
      }).then(r => {

        r.data.result.rows.forEach(r => r.editing = false);
        sheet.dataTable = r.data;
      });
    },
    accept() {
      this.$service.import.accept({
        params: {
          importer: this.importerName
        },
        data: {
          batchId: this.batchId,

        }
      }).then(r => {
        this.next();
        if (r.success){
          alert("导入成功!", "提示","success");
        }
        else{
          alert("导入失败，请检查数据格式是否正确!", "提示","error");
        }

        let data = r.data;
        this.batchId = data.batchId;
        if (data.groups && data.groups.length > 0){
          this.importGroup = data.groups[0];

          //this.loadPreview();
        }
      });
    },
    onUploadError(error, file){
      this.$store.commit("loading", false);
    },
    onBeforeUpload(file){
      this.$store.commit("loading", true);
      return new Promise((resolve, reject) => {
        let max = this.maxFileLength;
        if (file.size > max * 1024){
          alert(`上传文件不可超过${max}kb！`, "提示", "warning");
          reject();
          this.$store.commit("loading", false);
        }
        else{
          resolve();
        }

      });
    },
    tabClick(tab){

    },
    undo(row){
      confirm('该操作将导致当前数据行的更改丢失，继续吗？', '提示', 'warn', ()=>{
        this.$service.import.undo({
          params: {
            importer: this.importerName
          },
          data: {
            batchId: this.batchId,
            fileId: this.importGroup.file.fileId,
            name: this.sheetName,
            rowIndex: row.rowIndex
          }
        }).then(r => {
          if (r.success)
            this.resetRow(row, r.data);
        });
      });
    },
    remove(row){

      confirm('确定要删除此行吗？', '提示', 'warn', ()=>{
        this.$service.import.remove({
          params: {
            importer: this.importerName
          },
          data: {
            batchId: this.batchId,
            fileId: this.importGroup.file.fileId,
            name: this.sheetName,
            rowIndex: row.rowIndex
          }
        }).then(r => {
          if (r.success)
            this.resetRow(row, r.data);
        });
      });
    },
    update(row){

      confirm('确定要更新此行吗？', '提示', 'warn', ()=>{
        this.$service.import.update({
          params: {
            importer: this.importerName
          },
          data: {
            batchId: this.batchId,
            fileId: this.importGroup.file.fileId,
            name: this.sheetName,
            rowIndex: row.rowIndex,
            data: row.dataItem
          }
        }).then(r => {
          if (r.success)
            row.editing = false;
            this.resetRow(row, r.data);
        });
      });
    },
    resetRow(row, rowItem){
      row.state = rowItem.state;
      row.data = rowItem.data;
    },
    rowStyle(scope){
      let row = scope.row;
      if (row.state == "Removed")
        return {"color": "#d30f0fe0", "font-weight": "bolder", "text-decoration-line": "line-through", "text-decoration-color": "#d30f0fe0" };
      else if(row.state == "Changed")
        return {"color": "#398febc2", "font-weight": "bolder"};
      else
        return '';
    },
    reset(){
      confirm('重新上传操作将导致前期上传的文件及预览数据的更改全部丢失，继续请点击确定？', '提示', 'warn', this.init);
    }
  },
};
</script>
<style scoped>
</style>
